<template>
  <div class="artical-list">
    <!-- 下拉刷新组件 -->
    <van-pull-refresh
      v-model="isRefreshing"
      @refresh="onRefresh"
      success-text="刷新成功"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <!-- 因为很多重复，类似于文章封面显示，故封装成组件使用 -->
        <Article
          v-for="(article, index) in articles"
          :key="index"
          :article="article"
        ></Article>
        <!-- <van-cell
          v-for="(article, index) in articles"
          :key="index"
          :title="article.title"
        /> -->
      </van-list>
    </van-pull-refresh>
    <!-- 通过list组件显示文章 -->
  </div>
</template>

<script>
import Article from '../../../components/Article.vue'
export default {
  name: 'ArticalList',
  components: { Article },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      articles: [],
      loading: false,
      finished: false,
      timestamp: Date.now(), // 当前时间戳，以便控制页码数据
      isRefreshing: false // 下拉刷新控制
    }
  },
  methods: {
    async onLoad () {
      //  1.加载完毕后进行异步请求数据
      // 注意请求携带参数的写法
      const { data: res } = await this.$https.get('/app/v1_1/articles', {
        params: {
          channel_id: this.channel.id,
          timestamp: this.timestamp,
          with_top: 1
        }
      })

      // 2.将文章数据push进应有的数据，可以实时渲染
      this.articles.push(...res.data.results)
      // 3.将loading关闭
      this.loading = false
      // 4.当数据没有之后则关闭
      if (!res.data.results) { this.finished = true } else this.timestamp = res.data.pre_timestamp
    },
    async onRefresh () {
      const { data: res } = await this.$https.get('/app/v1_1/articles', {
        params: {
          channel_id: this.channel.id,
          timestamp: Date.now(), // 下拉刷新永远传最新的时间戳
          with_top: 1
        }
      })

      // 2.将文章数据push进应有的数据，可以实时渲染
      this.articles.unshift(...res.data.results)
      this.isRefreshing = false
    }
  }
}
</script>

<style scoped lang="less">
// 对list组件进行固定定位，防止样式效果被底部遮挡，上半部跟随
.artical-list {
  position: fixed;
  left: 0;
  top: 90px;
  right: 0;
  bottom: 50px;
  overflow-y: auto;
}
</style>
